// pages/home/home.js
import Request from '../../../utils/request.js'
import {
  navigateTo
} from "../../../utils/util.js";
let app = getApp()
let store = app.store
const accountInfo = wx.getAccountInfoSync()
const env = accountInfo.miniProgram.envVersion
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navTitle: app.globalData.ENVIRONMENT_CONFIG.homeHosTitle,
    navBarHeight: 0, //导航栏高度
    showIcon: true,
    showNavSearch: false,
    showSearch: true,
    commonDepartments: [], //全部科室
    concernedDoctors: [], //我关注的医生
    doctorsData: [], //全部医生列表
    requesting: false,
    end: false,
    emptyShow: false,
    emptyText: "暂无数据",
    pageNo: 1,
    tabs: ['我的报名'],
    currentTab: 0,
    swiperList: [],
    broadcast: {
      broadcastTitle: '人脸识别',
      skipUrl: '/pages/home/face/face',
      needLogin: true
    },
    postContent:'<p><br></p><p><span style="color: rgb(38, 38, 38);"> MOTIF飞盘奥森皮卡（Pickup）<br></span></p><p><span style="color: rgb(38, 38, 38);">~ 报名成功后，请联系微信：13466629143，加入MOTIF活动群。<br></span></p><p><span style="color: rgb(38, 38, 38);">适合哪些人参加？</span></p><p><span style="color: rgb(38, 38, 38);">- 了解基础比赛规则、有5次以上比赛经验的盘友最佳。</span></p><p><span style="color: rgb(38, 38, 38);">- 零基础不适合。<br></span></p><p><span style="color: rgb(38, 38, 38);">* 说明：</span></p><p><span style="color: rgb(38, 38, 38);">- 接受以Line（组队）形式报名；</span></p><p><span style="color: rgb(38, 38, 38);">- 每条Line（每队） 报名费用420元；</span></p><p><span style="color: rgb(38, 38, 38);">- 每条Line（每队）至少6人，建议最多不超过10人，至少3名女生；（6人费用人均70；10人费用人均42元）</span></p><p><span style="color: rgb(38, 38, 38);">- 按照Line形式报名的，队内换人该Line自行决定；</span></p><p><span style="color: rgb(38, 38, 38);">- 以个人形式报名的，接受组织方组队安排。<br></span></p><p><span style="color: rgb(38, 38, 38);">时间与地点：</span></p><p><span style="color: rgb(38, 38, 38);">周六 17:50-20:00</span></p><p><span style="color: rgb(38, 38, 38);">-17:50 集合</span></p><p><span style="color: rgb(38, 38, 38);">-17:50-18:10 热身 &amp; 自我介绍</span></p><p><span style="color: rgb(38, 38, 38);">-18:10-19:50 分组比赛</span></p><p><span style="color: rgb(38, 38, 38);">-19:50-20:00 合影 &amp; 总结<br></span></p><p><span style="color: rgb(38, 38, 38);">地点：奥森公园南</span></p>'
  },
  //点击切换
  tabChangeHandler: function(event) {
    let that = this;
    let idx = event.currentTarget.dataset.idx;
    if (this.data.currentTab === idx) {
      return false;
    } else {
      this.setData({
        currentTab: idx
      }, function() {
        // that.updateList();
      });
    }
  },
  // 获取我关注的医生列表
  findByPatientId(showAvatar) {
    let id = store.getState().systemLoginData.userId;
    let param = {
        patientId: id,
        userId: id,
        online: '0'
    };
    if(env !== 'develop'){
        params.online = '1';
    }
    Request.getRequest('/favoriteDoctor/findByUserId', param).then(data => {
      console.log("----", data)
      var doctorinfolist = data.data || []
      doctorinfolist.forEach(function (element) {
        // element.AmOrPm

        element.AmOrPm = element.amOrPm
        element.ChargeRegister = element.chargeRegister
        element.ChargeRegisterAll = element.chargeRegisterAll
        element.ChargeTreatment = element.chargeTreatment
        element.CheckDT = element.checkDT
        element.ClinicID = element.clinicID
        element.ClinicName = element.clinicName
        element.DeptType = element.deptType
        element.DiagTreatTypeCode = element.diagTreatTypeCode
        element.DiagTreatTypeName = element.diagTreatTypeName
        element.DoctorDesc = element.doctorIntroduction
        element.DoctorID = element.doctorID
        element.DoctorName = element.doctorName
        element.DoctorPosition = element.workCodeName
        // element.DutyStartHour = element.
        // element.DutyStopHour = element.
        element.SchedulingID = element.schedulingID
        element.SpecialDiseasesCode = element.specialDiseasesCode
        element.StopOutPatFlag = element.stopOutPatFlag
        element.SurplusNum = element.surplusNum
        element.visitTotal = element.visTotals
        element.ChargeRegister = element.ChargeRegisterAll//会诊费用
        element.ChargeRegisterAll = element.ChargeRegisterAll
        element.StopOutPatFlag = element.schedulingID ? 0 : 1//是否停诊
        element.logo = showAvatar ? app.globalData.ENVIRONMENT_CONFIG.imgBaseUrl + element.doctorId + '.jpg' : '/images/doctor-icon.png'
      })
      this.setData({
        concernedDoctors: doctorinfolist
      });
    })
  },
  // 获取全部科室列表
  outPatBookingClinic() {
    Request.getRequest('/outPatBookClinic/findClinicList', {
      level: 1
    }).then(data => {
      // console.log("outPatBookingClinic", data.RecordList.RecordInfo)
      // let departmentlist = data.RecordList.RecordInfo
      // console.log('departmentlist', departmentlist)
      // if (!Array.isArray(departmentlist)) {
      //   console.log('type error!')
      //   let a = []
      //   a.push(departmentlist)
      //   departmentlist = a;
      //   // return
      // }
      // let SupClinicNameArr=[];
      // departmentlist.forEach((item,index)=>{
      //   if (SupClinicNameArr.indexOf(item.SupClinicName)== -1){
      //     SupClinicNameArr.push(item);
      //   }
      // });
      console.log(data.data)
      this.setData({
        commonDepartments: data.data
      });
    })
  },
  // 获取全部医生列表
  doctorInfo() {
    this.setData({
      requesting: true,
      emptyShow: false,
      end: false,
    });
    Request.getRequest('/params/params?paramType=doctorSetting').then(res => {
      let data = res.data
      let settings = {}
      data.forEach(item => {
        settings[item.paramName] = item.paramValue
      })
      let showAvatar = settings['showAvatar'] !== 'false'
      this.getDoctorList(settings['docTotal'], showAvatar)
      this.findByPatientId(showAvatar)

      store.dispatch({
        type: 'set_DoctorSetting',
        data: {
          showAvatar: showAvatar,
          isInputEvaluation: settings['isInputEvaluation'] === 'true',
          showEvaluation: settings['showEvaluation'] !== 'false'
        }
      });
    }, error => {
      this.getDoctorList(4, true)
      this.findByPatientId(true)
    })
  },
  getDoctorList(size, showAvatar) {
    let param = {
        noPic: 1,
        pageNo: this.data.pageNo,
        pageSize: size || 4
    };
    if(env !== 'develop'){
        params.online = '1';
    }
    Request.postRequest('/api/common/findTadministrativeOrDoctorListNoPage', param).then(data => {
      console.log("alldoctorInfo", data)
      // let doctorsRecommendData = data.RecordList.RecordInfo;


      //整理一下搜索接口返回的医生数据的数据结构，和首页的保持一致
      let doctorInfo = [];
      data.data.forEach((item, index) => {
        doctorInfo.push({
          appraise: item.averageLevel * 1,//评分
          visitTotal: item.visTotals,//问诊量
          DoctorDesc: item.doctorIntroduction,//擅长
          DiagTreatTypeName: item.visStatusDescrib,//问诊方式
          // StopOutPatFlag: undefined,//是否停诊
          StopOutPatFlag: item.SchedulingID ? 0 : 1,//是否停诊
          DoctorPosition: item.workCodeName,//职称
          DoctorName: item.doctorName,//医生姓名
          DoctorID: item.doctorId,//医生ID
          ClinicName: item.clinicName,//科室名字
          ClinicID: item.clinicId,//科室id
          DeptType: item.deptType,
          ChargeRegister: item.ChargeRegisterAll,//会诊费用
          ChargeRegisterAll: item.ChargeRegisterAll,
          logo: showAvatar ? app.globalData.ENVIRONMENT_CONFIG.imgBaseUrl + item.doctorId + '.jpg' : '/images/doctor-icon.png'
        });
      });
      
      doctorInfo = [{appraise: 1,//评分
        visitTotal: 5,//问诊量
        DoctorDesc: "dddddxxxx",//擅长
        DiagTreatTypeName: "vv",//问诊方式
        // StopOutPatFlag: undefined,//是否停诊
        StopOutPatFlag: 1,//是否停诊
        DoctorPosition: "职称",//职称
        DoctorName: "dddxingming",//医生姓名
        DoctorID: "2222",//医生ID
        ClinicName: "keshimingcheng",//科室名字
        ClinicID: "23435",//科室id
        DeptType: "3",
        ChargeRegister: 22,//会诊费用
        ChargeRegisterAll: "dd"},
        {appraise: 1,//评分
          visitTotal: 5,//问诊量
          DoctorDesc: "dddddxxxx",//擅长
          DiagTreatTypeName: "vv",//问诊方式
          // StopOutPatFlag: undefined,//是否停诊
          StopOutPatFlag: 1,//是否停诊
          DoctorPosition: "职称",//职称
          DoctorName: "dddxingming",//医生姓名
          DoctorID: "2222",//医生ID
          ClinicName: "keshimingcheng",//科室名字
          ClinicID: "23435",//科室id
          DeptType: "3",
          ChargeRegister: 22,//会诊费用
          ChargeRegisterAll: "dd"}
      
      ];

      console.log("doctorsData", doctorInfo)
      this.setData({
        requesting: false,
        emptyShow: true,
        end: true,
        doctorsData: doctorInfo
      });
    }, error => {
      this.setData({
        requesting: false,
        emptyShow: true,
        end: true,
        doctorsData: []
      });
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // this.findByPatientId();
    // this.outPatBookingClinic();
     this.doctorInfo();
    this.loadAuth();
    this.loadSwipeList();
    //this.getQrCodeSetting()

    // 获取进入小程序参数
    let enterParam = wx.getEnterOptionsSync()
    let scene = decodeURIComponent(enterParam.query.scene)
    console.log('enter scene', scene)
    if (scene && scene.split('=').length > 1) {
      app.globalData.agentNum = scene.split('=')[1]
    }
    app.globalData.enterTime = new Date()
  },

  loadAuth: function() {
    if (wx.getStorageSync("token")) {
      store.dispatch({
        type: 'set_LoginData',
        data: {
          token: wx.getStorageSync("token"),
          userId: wx.getStorageSync("userId"),
          mobile: wx.getStorageSync("mobile"),
          imUserName: wx.getStorageSync("imUserName"),
          imPassword: wx.getStorageSync("imPassword"),
          imId: wx.getStorageSync("imId"),
        }
      });
    }
  },
  loadSwipeList: function() {
    Request.getRequest('/wxPicture/all').then(res => {
      if (res.code === 1 && res.data && res.data.length > 0) {
        let list = res.data
        // 获取轮播列表，并进行过滤和排序
        let swiperList = list.filter(item => item.isShow && item.broadcastLocation === 0)
        swiperList.sort((a, b) => a.rank - b.rank)
        swiperList.length > 0 && this.setData({
          swiperList
        })

        let broadcast = list.filter(item => item.isShow && item.broadcastLocation === 1)
        broadcast.length > 0 && this.setData({
          broadcast: broadcast[0]
        })

        broadcast = [{broadcastLocation: 0,
          createdAt: "2021-01-04 23:05:22",
          createdBy: "2c9180846e3aca04016e3af4a3b90010",
          createdByName: "qiuying",
          dataVersion: 2,
          deletedStatus: "0",
          id: "2c91808376cdda820176cdee66640010",
          imageUrl: "https://wx.jyyy.com.cn:8092/static/photo/1609832086503.png",
          isShow: false,
          needLogin: true,
          rank: 4,
          skipUrl: "/pages/home/nat/nat",
          updatedAt: "2021-01-04 23:05:22",
          updatedBy: "2c9180846e3aca04016e3af4a3b90010",
          updatedByName: "qiuying"}];
          swiperList = broadcast;
          this.setData({
            broadcast:broadcast
          })
        console.info('list-------------->',list);
      }
    })
  },
  getQrCodeSetting: function() {
    Request.getRequest('/params/params?paramName=EXTEND_CODE_EFFECTIVE_TIME').then(res => {
      if (res.code === 1 && res.data.length > 0) {
        let timeSetting = res.data[0]
        let qrCodeTimeout = timeSetting.paramValue
        app.globalData.qrCodeTimeout = qrCodeTimeout
      }
    }).catch(err => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    console.log(app.globalData.statusBarHeight);
    this.setData({
      navBarHeight: app.globalData.statusBarHeight + app.globalData.titleBarHeight
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // this.findByPatientId();
    // this.outPatBookingClinic();
    // this.doctorInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  // onPageScroll: function (e) {
  //   console.log(e.scrollTop);
  //   if(e.scrollTop>=54){
  //     this.setData({
  //       showSearch:false,
  //       showNavSearch:true
  //     });
  //   }else{
  //     this.setData({
  //       showSearch:true,
  //       showNavSearch:false
  //     });
  //   }
  // },
  goSearch: function() {
    navigateTo({
      url: "/pages/home/search/search"
    });
  },
  goDoctorList() {
    navigateTo({
      url: "/pages/home/doctorList/doctorList?entryID=1"
    });
  },
  goPage(event) {
    let dataset = event.currentTarget.dataset
    let url = dataset.url
    let needLogin = dataset.needlogin
    if (needLogin) {
      navigateTo({
        url: url
      });
    } else {
      wx.navigateTo({
        url: url
      });
    }
  },
  goNurseApply: function() {
    navigateTo({
      url: "/pages/me/manage/index?model=nurse&title=陪护人管理-选择就诊人"
    });
  },
  goFaceAuth: function() {
    navigateTo({
      url: '/pages/home/face/face',
    });
  },
  showGuide: function() {
    wx.navigateTo({
      url: "/pages/home/serviceGuide/serviceGuide"
    });
  }
})
